package com.nwpu.am.controller.admin;

import com.nwpu.am.constant.ErrorConstant;
import com.nwpu.am.pojo.dto.PartFindDTO;
import com.nwpu.am.pojo.dto.PurchaseItemDTO;
import com.nwpu.am.pojo.dto.UserAddDTO;
import com.nwpu.am.pojo.entity.Part;
import com.nwpu.am.pojo.entity.PurchaseItem;
import com.nwpu.am.pojo.entity.User;
import com.nwpu.am.result.Result;
import com.nwpu.am.service.PartService;
import com.nwpu.am.service.PurchaseItemService;
import com.nwpu.am.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * AdminController
 *
 * @author Roy
 * @version 1.0
 * {@code @date} 2024/6/5
 */

@RestController
@RequestMapping("/admin")
@Slf4j
@Api(tags = "管理员接口")
public class AdminController {

    @Resource
    private UserService userService;

    @Resource
    private PartService partService;

    @Resource
    private PurchaseItemService purchaseItemService;

    @PostMapping("/add")
    @ApiOperation("添加用户")
    @RequiresPermissions("admin:add")
    public Result<String> add(@RequestBody @Validated UserAddDTO userAddDTO) {
        // 验证用户名
        User user = userService.findByUsername(userAddDTO.getUsername());
        if (user == null) {
            userService.addUser(userAddDTO);
        } else {
            return Result.error(ErrorConstant.USER_HAS_EXISTED);
        }
        return Result.success();
    }

    @GetMapping("/findPart")
    @ApiOperation("查找零件")
    @RequiresPermissions("admin:findPart")
    public Result<ArrayList<Part>> findPart(@RequestBody @Validated PartFindDTO partFindDTO) {
        return Result.success(partService.findPart(partFindDTO));
    }

    @PostMapping("/submitPurchase")
    @ApiOperation("提交采购订单")
    @RequiresPermissions("admin:submitPurchase")
    public PurchaseItem submitPurchase(@RequestBody @Validated PurchaseItemDTO purchaseItemDTO) {
        return purchaseItemService.submitPurchase(purchaseItemDTO);
    }

}
